package com.qf.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author AzureSky_X
 * @Date 2021/1/8 14:31
 * @Version 1.0
 *
 * 处理中文乱码
 */

//如果这里是/* 那么连html的数据都要过滤
//@WebFilter(value = "/*",
//        initParams = {
//                //这些都是拓展名，用于区别当前资源是什么类型
//                @WebInitParam(name="extNames",value = ".html,.css,.js,jpg,jsp")
//        })
public class EncodingFilter implements Filter {
    //创建数组储存拓展名
    private String[] extNames;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String names = filterConfig.getInitParameter("extNames");
        //通过","进行分割提取拓展名
        extNames=names.split(",");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;

        String uri=request.getRequestURI();
        /**
         * flag 标识是否要处理中文乱码
         * true：不处理
         * false：处理
         */
        boolean flag=false;
        if (uri != null){
            for (String extName:extNames){
                //包含在extNames中的拓展名结尾的文件，不处理乱码问题
                if (uri.endsWith(extName)){
                    flag=true;
                    //查询到就提前退出循环，提高效率
                    break;
                }
            }
        }
        //解决中文乱码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //放行
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
